package teacher.core;

import java.lang.reflect.Method;
import java.util.Iterator;



public class DefaultActionInvocation implements ActionInvocation{
	private Iterator<Interceptor> interceptors;
	private Object action;
	private Result result;
	private String resultCode;
	private ActionProxy proxy;
	private boolean executed = false;
	
	public ActionProxy getProxy() {
		return proxy;
	}

	public void setProxy(ActionProxy proxy) {
		this.proxy = proxy;
	}

	public String invoke() {
		//如果有拦截器,执行拦截器的interceptor方法
		if(interceptors.hasNext()){
			resultCode = interceptors.next().interceptor(this);
		}else{
			//如果所有拦截器执行完毕
			try {
				resultCode = execAction("execute");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//根据resultCode去配置中寻找result定义信息，创建一个Result对象
		if(!executed){
			execResult();
			executed = true;
		}
		return resultCode;
	}
	
	private void execResult(){
		result = proxy.getResult(resultCode);//根据resultCode创建Result对象
		result.execute(this);
	}
	
	private String execAction(String method) throws Exception{
		if(action == null){
			return "success";
		}
		Method mth = action.getClass().getMethod(method, null);
		return (String)mth.invoke(action, null);
	}

	public Object getAction() {
		return action;
	}

	public void setAction(Object action) {
		this.action = action;
	}

	public Iterator<Interceptor> getInterceptors() {
		return interceptors;
	}

	public void setInterceptors(Iterator<Interceptor> interceptors) {
		this.interceptors = interceptors;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public String getResultCode() {
		return resultCode;
	}

	public void setResultCode(String resultCode) {
		this.resultCode = resultCode;
	}

}
